import React from 'react';
import { Card, Row, Col, Form, Select, DatePicker, Radio, Button, Table, Space, Typography, InputNumber } from 'antd';
import { LineChartOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
// 统一封装的 ECharts 引入
import echarts from '../../utils/echarts';

const { RangePicker } = DatePicker;
const { Text } = Typography;

function seededRandom(seed) {
  let x = Math.sin(seed) * 10000;
  return x - Math.floor(x);
}

function formatCSV(rows) {
  const headers = Object.keys(rows[0] || {});
  const escape = (v) => `"${String(v ?? '').replace(/"/g, '""')}"`;
  const lines = [headers.join(',')].concat(rows.map(r => headers.map(h => escape(r[h])).join(',')));
  return lines.join('\n');
}

export default function ProductProfit() {
  const [form] = Form.useForm();
  const pieRef = React.useRef(null);
  const lineRef = React.useRef(null);
  const barRef = React.useRef(null);
  const pieChart = React.useRef(null);
  const lineChart = React.useRef(null);
  const barChart = React.useRef(null);

  const products = React.useMemo(() => (
    [
      { id: 'P001', name: '商品A' },
      { id: 'P002', name: '商品B' },
      { id: 'P003', name: '商品C' },
      { id: 'P004', name: '商品D' },
      { id: 'P005', name: '商品E' },
      { id: 'P006', name: '商品F' },
    ]
  ), []);

  const [filters, setFilters] = React.useState({
    type: 'amount',
    range: [dayjs().subtract(6, 'day'), dayjs()],
    productIds: [],
    topN: 5,
  });

  const [tableData, setTableData] = React.useState([]);

  const dateLabels = React.useMemo(() => {
    const start = filters.range?.[0] || dayjs().subtract(6, 'day');
    const end = filters.range?.[1] || dayjs();
    const days = end.diff(start, 'day') + 1;
    return Array.from({ length: days }, (_, i) => start.add(i, 'day').format('YYYY-MM-DD'));
  }, [filters.range]);

  const calcForProduct = (id) => {
    let totalCount = 0;
    let totalAmount = 0;
    const series = dateLabels.map((d, idx) => {
      const seed = parseInt(id.replace(/\D/g, ''), 10) * 100 + idx;
      const base = 10 + Math.floor(seededRandom(seed) * 90);
      const count = Math.floor(base * (0.5 + seededRandom(seed + 7)) / 10);
      const amount = base * (0.8 + seededRandom(seed + 17));
      totalCount += count;
      totalAmount += amount;
      return { date: d, count, amount: Number(amount.toFixed(2)) };
    });
    return { totalCount, totalAmount: Number(totalAmount.toFixed(2)), series };
  };

  const refreshData = React.useCallback(() => {
    const selected = filters.productIds.length ? products.filter(p => filters.productIds.includes(p.id)) : products;
    const rows = selected.map(p => {
      const calc = calcForProduct(p.id);
      return {
        productId: p.id,
        productName: p.name,
        times: Math.floor(calc.totalCount / 3),
        num: calc.totalCount,
        sales: calc.totalAmount,
      };
    });
    setTableData(rows);

    const pieData = rows.map(r => ({ name: `${r.productName}`, value: filters.type === 'amount' ? r.sales : r.num }));
    const sorted = [...rows].sort((a, b) => (filters.type === 'amount' ? b.sales - a.sales : b.num - a.num)).slice(0, filters.topN);
    const barNames = sorted.map(r => r.productName);
    const barValues = sorted.map(r => filters.type === 'amount' ? Number(r.sales.toFixed(2)) : r.num);

    const sumByDate = dateLabels.map((d, idx) => {
      let sum = 0;
      selected.forEach(p => {
        const calc = calcForProduct(p.id);
        const val = filters.type === 'amount' ? calc.series[idx].amount : calc.series[idx].count;
        sum += val;
      });
      return Number(sum.toFixed(2));
    });

    if (pieRef.current) {
      if (!pieChart.current) pieChart.current = echarts.init(pieRef.current);
      pieChart.current.setOption({
        title: { text: '商品占比', left: 'center' },
        tooltip: { trigger: 'item' },
        legend: { bottom: 0 },
        series: [{ type: 'pie', radius: '50%', data: pieData }],
      }, { notMerge: true });
      pieChart.current.resize();
    }
    if (lineRef.current) {
      if (!lineChart.current) lineChart.current = echarts.init(lineRef.current);
      lineChart.current.setOption({
        title: { text: '商品收益趋势', left: 'center' },
        tooltip: { trigger: 'axis' },
        grid: { left: 40, right: 24, top: 56, bottom: 36 },
        xAxis: { type: 'category', data: dateLabels },
        yAxis: { type: 'value' },
        series: [{ name: filters.type === 'amount' ? '金额' : '数量', type: 'line', smooth: true, data: sumByDate }],
      }, { notMerge: true });
      lineChart.current.resize();
    }
    if (barRef.current) {
      if (!barChart.current) barChart.current = echarts.init(barRef.current);
      barChart.current.setOption({
        title: { text: `商品排行 Top ${filters.topN}`, left: 'center' },
        tooltip: { trigger: 'axis' },
        grid: { left: 40, right: 24, top: 56, bottom: 36 },
        xAxis: { type: 'category', data: barNames },
        yAxis: { type: 'value' },
        series: [{ type: 'bar', data: barValues }],
      }, { notMerge: true });
      barChart.current.resize();
    }
  }, [filters, products, dateLabels]);

  React.useEffect(() => {
    refreshData();
  }, [refreshData]);

  React.useEffect(() => {
    const onResize = () => {
      pieChart.current?.resize();
      lineChart.current?.resize();
      barChart.current?.resize();
    };
    window.addEventListener('resize', onResize);
    return () => {
      window.removeEventListener('resize', onResize);
      pieChart.current?.dispose();
      lineChart.current?.dispose();
      barChart.current?.dispose();
    };
  }, []);

  const onSearch = () => {
    const v = form.getFieldsValue();
    setFilters(prev => ({
      ...prev,
      type: v.type,
      range: v.range,
      productIds: v.productIds || [],
      topN: v.topN || 5,
    }));
  };

  const onReset = () => {
    form.resetFields();
    setFilters({ type: 'amount', range: [dayjs().subtract(6, 'day'), dayjs()], productIds: [], topN: 5 });
  };

  const exportCSV = () => {
    if (!tableData.length) return;
    const csv = formatCSV(tableData.map(r => ({
      商品编号: r.productId,
      商品名称: r.productName,
      交易次数: r.times,
      销售数量: r.num,
      销售金额: r.sales,
    })));
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `商品收益_${dayjs().format('YYYYMMDD_HHmmss')}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  };

  const columns = [
    { title: '商品编号', dataIndex: 'productId', key: 'productId' },
    { title: '商品名称', dataIndex: 'productName', key: 'productName' },
    { title: '交易次数', dataIndex: 'times', key: 'times' },
    { title: '销售数量', dataIndex: 'num', key: 'num' },
    { title: '销售金额', dataIndex: 'sales', key: 'sales', render: (v) => v?.toFixed ? v.toFixed(2) : v },
  ];

  const summary = () => {
    const totalTimes = tableData.reduce((s, r) => s + r.times, 0);
    const totalNum = tableData.reduce((s, r) => s + r.num, 0);
    const totalSales = tableData.reduce((s, r) => s + r.sales, 0);
    return (
      <Table.Summary.Row>
        <Table.Summary.Cell index={0}>合计</Table.Summary.Cell>
        <Table.Summary.Cell index={1}></Table.Summary.Cell>
        <Table.Summary.Cell index={2}>{totalTimes}</Table.Summary.Cell>
        <Table.Summary.Cell index={3}>{totalNum}</Table.Summary.Cell>
        <Table.Summary.Cell index={4}>{totalSales.toFixed(2)}</Table.Summary.Cell>
      </Table.Summary.Row>
    );
  };

  return (
    <Card
      title={
        <Space align="center">
          <LineChartOutlined style={{ color: '#fa8c16', fontSize: 18 }} />
          <Text strong>商品收益</Text>
        </Space>
      }
    >
      <Form form={form} layout="inline" initialValues={filters} style={{ marginBottom: 12 }}>
        <Form.Item label="统计类型" name="type">
          <Radio.Group>
            <Radio.Button value="amount">金额</Radio.Button>
            <Radio.Button value="count">数量</Radio.Button>
          </Radio.Group>
        </Form.Item>
        <Form.Item label="时间范围" name="range">
          <RangePicker allowClear={false} />
        </Form.Item>
        <Form.Item label="商品" name="productIds">
          <Select style={{ width: 220 }} mode="multiple" allowClear placeholder="选择商品">
            {products.map(p => <Select.Option key={p.id} value={p.id}>{p.name}({p.id})</Select.Option>)}
          </Select>
        </Form.Item>
        <Form.Item label="TopN" name="topN">
          <InputNumber min={1} max={10} style={{ width: 80 }} />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button type="primary" onClick={onSearch}>查询</Button>
            <Button onClick={onReset}>重置</Button>
            <Button onClick={exportCSV}>导出CSV</Button>
          </Space>
        </Form.Item>
      </Form>

      <Row gutter={[12, 12]}>
        <Col xs={24} lg={8}>
          <Card size="small" title="商品占比">
            <div ref={pieRef} style={{ height: 280 }} />
          </Card>
        </Col>
        <Col xs={24} lg={16}>
          <Card size="small" title="商品收益趋势">
            <div ref={lineRef} style={{ height: 280 }} />
          </Card>
        </Col>
        <Col xs={24}>
          <Card size="small" title="商品排行">
            <div ref={barRef} style={{ height: 300 }} />
          </Card>
        </Col>
      </Row>

      <Card size="small" title="明细表" style={{ marginTop: 12 }}>
        <Table rowKey="productId" columns={columns} dataSource={tableData} pagination={{ pageSize: 8 }} summary={summary} />
      </Card>
    </Card>
  );
}